# app/auth.py
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from . import models, database

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password):            #密码加密
    return pwd_context.hash(password)

def verify_password(plain_password, hashed_password):   #密码验证
    return pwd_context.verify(plain_password, hashed_password)

def get_user_by_username(db: Session, username: str):   # 用户查询与认证
    return db.query(models.User).filter(models.User.username == username).first()

def authenticate_user(db: Session, username: str, password: str):
    user = get_user_by_username(db, username)
    if not user or not verify_password(password, user.hashed_password):
        return None   #认证失败
    return user       #认证成功
